package store

import (
	"fmt"
	"github.com/wi-cuckoo/eastlake/web/model"
)

// GetUser ...
func (o *orm) UserInfo(uid int) (*model.User, error) {
	u := new(model.User)
	err := o.Where("uid = ?", uid).First(u).Error
	return u, err
}

func (o *orm) UserInfoByUsername(username string) (*model.User, error) {
	u := new(model.User)
	err := o.Where("username = ?", username).First(u).Error
	return u, err
}

// GetUser ...
func (o *orm) QueryUsers(opts *model.UserQueryOpts) (int64, []*model.User, error) {
	var (
		total int64
		users []*model.User
	)
	db := o.Model(new(model.User))
	if opts.Username != "" {
		db = db.Where("username like ?", fmt.Sprintf("%%%s%%", opts.Username))
	}
	if opts.Nickname != "" {
		db = db.Where("nickname like ?", fmt.Sprintf("%%%s%%", opts.Nickname))
	}
	if opts.Key != "" {
		db = db.Where("nickname like ? or username like ?", fmt.Sprintf("%%%s%%", opts.Key), fmt.Sprintf("%%%s%%", opts.Key))
	}
	if len(opts.Usernames) != 0 {
		db = db.Where("username in (?)", opts.Usernames)
	}
	if err := db.Count(&total).Error; err != nil {
		return 0, nil, err
	}
	err := db.Find(&users).Limit(opts.Size).Offset((opts.Page - 1) * opts.Size).Error
	return total, users, err
}

// CreateUser ...
func (o *orm) CreateUser(u *model.User) error {
	return o.Create(u).Error
}

// UpdateUser ...
func (o *orm) UpdateUser(uid int, u *model.User) error {
	return o.Model(u).Where("uid = ?", uid).Updates(u).Error
}
